/* 
 * File:   DeliveryClient.cpp
 * Author: bd
 * 
 * Created on April 2, 2011, 10:28 AM
 */

#include "DeliveryClient.hpp"
#include "SmppDeliveryClient.hpp"
#include "RpcDeliveryClient.hpp"
#include "inc.hpp"

DeliveryClient::DeliveryClient(const std::string& connStr) :
connected_(false)
{
    std::map<std::string, std::string> params;
    parse_connection_string(connStr, params);

    username_ = params["username"];
    password_ = params["password"];
    targetUrl_ = params["url"];
}

DeliveryClient::~DeliveryClient()
{
}

void parse_connection_string(const std::string& connStr, std::map<std::string, std::string>& params)
{

    //username@smpp://url password
    size_t at = connStr.find('@');
    if (at == std::string::npos)
    {
        LOG(ERROR) << "couldn't parse connection string:\n";
        return;
    }

    std::string username;
    username = connStr.substr(0, at);

    params["username"] = username;
    size_t protocol_end = connStr.find(':', at + 1);
    std::string protocol = connStr.substr(at + 1, protocol_end - at - 1);

    params["protocol"] = protocol;
    size_t url_end = connStr.find(' ', protocol_end + 2);
    std::string url = connStr.substr(protocol_end + strlen("://"), url_end - protocol_end - strlen("://"));
    params["url"] = url;

    LOG(INFO) << "target connection string - " <<
              "username:" << username << " " <<
              "protocol:" << protocol << " " <<
              "url:" << url;
}

void DeliveryClient::password(std::string password_)
{
    this->password_ = password_;
}

std::string DeliveryClient::password() const
{
    return password_;
}

void DeliveryClient::username(std::string username_)
{
    this->username_ = username_;
}

std::string DeliveryClient::username() const
{
    return username_;
}

void DeliveryClient::targetUrl(std::string targetUrl_)
{
    this->targetUrl_ = targetUrl_;
}

std::string DeliveryClient::targetUrl() const
{
    return targetUrl_;
}

void DeliveryClient::connected(bool connected_)
{
    this->connected_ = connected_;
}

bool DeliveryClient::connected() const
{
    return connected_;
}

DeliveryClientFactory::DeliveryClientFactory()
{

}

DeliveryClient::DeliveryClientPtr DeliveryClientFactory::create(const std::string& connStr)
{
    std::map<std::string, std::string> params;

    parse_connection_string(connStr, params);

    std::string protocol = params["protocol"];
    if (protocol == "smpp")
        return DeliveryClient::DeliveryClientPtr(new SmppDeliveryClient(connStr));
    else if (protocol == "rpc")
        return DeliveryClient::DeliveryClientPtr(new RpcDeliveryClient(connStr));
    else
        return DeliveryClient::DeliveryClientPtr();
}
